import {Message} from "@arco-design/web-vue";
import {useMapStore} from "./index";
import {saveCategoriesToStorage, saveToStorage} from "./storage";

// 分类管理功能
export const addNewCategory = () => {
    const store = useMapStore();

    const newCategory = {
        id: `category_${Date.now()}`,
        name: "新分类",
        order: store.addressCategories.length,
    };
    store.addressCategories.push(newCategory);
    saveCategoriesToStorage();
};

export const updateCategory = (categoryId: string, updates: any) => {
    const store = useMapStore();

    const category = store.addressCategories.find(c => c.id === categoryId);
    if (category) {
        Object.assign(category, updates);
        saveCategoriesToStorage();
    }
};

export const deleteCategory = (categoryId: string) => {
    const store = useMapStore();

    // 不能删除默认分类
    if (categoryId === "default") {
        Message.warning("不能删除默认分类");
        return;
    }

    const categoryIndex = store.addressCategories.findIndex(c => c.id === categoryId);
    if (categoryIndex > -1) {
        // 将使用该分类的地址改为默认分类
        store.addressList.forEach(address => {
            if (address.categoryId === categoryId) {
                address.categoryId = "default";
            }
        });

        store.addressCategories.splice(categoryIndex, 1);
        saveCategoriesToStorage();
        saveToStorage();
        Message.success("分类删除成功");
    }
};

export const moveCategory = (categoryId: string, direction: "up" | "down") => {
    const store = useMapStore();

    const index = store.addressCategories.findIndex(c => c.id === categoryId);
    if (index === -1) return;

    const newIndex = direction === "up" ? index - 1 : index + 1;
    if (newIndex < 0 || newIndex >= store.addressCategories.length) return;

    // 交换位置
    const temp = store.addressCategories[index];
    store.addressCategories[index] = store.addressCategories[newIndex];
    store.addressCategories[newIndex] = temp;

    // 更新order
    store.addressCategories.forEach((category, i) => {
        category.order = i;
    });

    saveCategoriesToStorage();
};
